package com.gsm.phimhanhdong;

import java.util.Calendar;
import java.util.Locale;

import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.astuetz.viewpager.extensions.PagerSlidingTabStrip;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gcm.GCMRegistrar;
import com.gsm.phimhanhdong.ContentNetworkInterface.CheckUpdateSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetAccesstokenSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetListPlaylistSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.GetPopUpSuccessEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.OnMenuItemClickEvent;
import com.gsm.phimhanhdong.ContentNetworkInterface.RegisterGCMSUCCess;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

import de.greenrobot.event.EventBus;

public class HomeActivity extends SlidingFragmentActivity implements
		OnClosedListener {
	public static final String REG_ID= "phimhanhdong2013";
	private static final String SENDER_ID = "787730237419";
	public static final int alarm_interval = 3 * 60 * 60 * 1000;
	public static final int alarm_interval_checkinstallApp = 3 * 24 * 60 * 60
			* 1000;

	private ViewPager viewPager;
	private Resources res;
	private HomeFragmentAdapter adapter;
	private EventBus eventBus;
	private BackgroundTasks bgTask;
	private Banner popup;

	private void setRecurringAlarm() {
		// we know mobiletuts updates at right around 1130 GMT.
		// let's grab new stuff at around 11:45 GMT, inexactly
		Calendar calendar = Calendar.getInstance();
		Intent intent = new Intent(this, CheckNewPhotoReciver.class);
		intent.putExtra("action", "notification");
		PendingIntent penddIntent = PendingIntent.getBroadcast(this, 0, intent,
				PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		try {
			alarms.cancel(penddIntent);
		} catch (Exception e) {
			Log.e("", "AlarmManager update was not canceled. " + e.toString());
		}
		alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP,
				calendar.getTimeInMillis() + alarm_interval, alarm_interval,
				penddIntent);
		Intent intent1 = new Intent(this, CheckInstallAppReciver.class);
		intent1.putExtra("action", "checkinstall_vloghot");
		PendingIntent penddIntent1 = PendingIntent.getBroadcast(this, 0,
				intent1, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager alarms1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		try {
			alarms1.cancel(penddIntent);
		} catch (Exception e) {
			Log.e("", "AlarmManager update was not canceled. " + e.toString());
		}
		alarms1.setInexactRepeating(AlarmManager.RTC_WAKEUP,
				calendar.getTimeInMillis() + alarm_interval_checkinstallApp,
				alarm_interval_checkinstallApp, penddIntent1);
	}

	private void createShortcut() {
		// TODO Auto-generated method stub
		if (!getSharedPreferences("videoyoutubeappota", 0).getBoolean(
				"install_shortcut", false)) {
			if (!appInstalledOrNot("com.appstoregp.vn")) {
				addShortcut();
				getSharedPreferences("videoyoutubeappota", 0).edit()
						.putBoolean("install_shortcut", true).commit();
			}
		}
	}

	private boolean appInstalledOrNot(String uri) {
		PackageManager pm = getPackageManager();
		boolean app_installed = false;
		try {
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			app_installed = true;
		} catch (PackageManager.NameNotFoundException e) {
			app_installed = false;
		}
		Log.e("", "appInstalledOrNot " + app_installed);
		return app_installed;
	}

	private void addShortcut() {
		// Adding shortcut for MainActivity
		// on Home screen
		Intent shortcutIntent = new Intent(Intent.ACTION_VIEW,
				Uri.parse("market://details?id=com.appstoregp.vn"));
		shortcutIntent.addCategory(Intent.CATEGORY_BROWSABLE);

		Intent addIntent = new Intent();
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "AppStoreVn ");
		addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(
						getApplicationContext(), R.drawable.ic_launcher));

		addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
		getApplicationContext().sendBroadcast(addIntent);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		createShortcut();
		EasyTracker.getInstance().setContext(this);
		setRecurringAlarm();
		EventBus.getDefault().register(this);
		eventBus = EventBus.getDefault();
		bgTask = new BackgroundTasks(this);
		registerGCMNotificationService();
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setTitle(
				getResources().getString(R.string.title_app_more));
		initView();
		if(getIntent()!=null && getIntent().getExtras()!=null){
			String title = getIntent().getStringExtra("title");
			String message = getIntent().getStringExtra(Constants.MESSAGE);
			AlertDialog.Builder builder = new Builder(HomeActivity.this);
			builder.setTitle(title)
					.setMessage(message)
					.setNegativeButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method
									// stub
									dialog.dismiss();
								}
							})
					.setNeutralButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
			AlertDialog dialog = builder.create();
			dialog.show();
		}
	}
	
	public void onEventMainThread(RegisterGCMSUCCess e){
		Log.e("", "RegisterGCMSUCCess success ");
		 GCMRegistrar.setRegisteredOnServer(this, true);
	}

	private void registerGCMNotificationService() {
		// TODO Auto-generated method stub
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) {
			// Registration is not present, register now with GCM
			Log.e("", "regID " + regId);
			GCMRegistrar.register(this, SENDER_ID);
		} else {
			Log.e("", "regID " + regId);
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(this)) {
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				boolean isrooted = RootUtil.isDeviceRooted();
				String root = null;
				if (isrooted) {
					root = "1";
				} else {
					root = "0";
				}
				try {
					bgTask.registerGCM(regId, root);
				} catch (NameNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public void onEventMainThread(GetListPlaylistSuccessEvent e) {
		getSupportActionBar().setTitle(e.playlists.get(0).getName());
	}

	private void initView() {
		// TODO Auto-generated method stub
		Log.e("", "intit view ");
		setContentView(R.layout.list_pager);
		res = getResources();

		viewPager = (ViewPager) findViewById(R.id.pager);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int pageMargin = dm.widthPixels / 48;
		adapter = new HomeFragmentAdapter(getSupportFragmentManager());
		viewPager.setOffscreenPageLimit(6);
		viewPager.setPageMargin(pageMargin);
		viewPager.setAdapter(adapter);
		PagerSlidingTabStrip indicator = (PagerSlidingTabStrip) findViewById(R.id.indicator);
		indicator.setTabStyleWhenChildCountSmall();
		indicator.setViewPager(viewPager);
		indicator.setIndicatorColorResource(R.color.app_indicator);
		int pixelSize = (int) (14 * dm.scaledDensity);
		indicator.setTextSize(pixelSize);

		// init menu frag
		setBehindContentView(R.layout.menu_frame);
		FragmentTransaction t = this.getSupportFragmentManager()
				.beginTransaction();
		MenuFragment mFrag = new MenuFragment();
		t.replace(R.id.menu_frame, mFrag);
		t.commit();

		// customize the SlidingMenu
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setFadeDegree(0.35f);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		sm.setOnClosedListener(this);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			toggle();
			return true;

		case R.id.about:
			Intent intent = new Intent(HomeActivity.this, AboutActivity.class);
			startActivity(intent);
			return true;

		case R.id.sort:
			AlertDialogManager am = new AlertDialogManager(HomeActivity.this);
			String[] items = getResources().getStringArray(R.array.more);
			am.showDialogWithItems(R.string.sort, items,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case 0:
								bgTask.onOptionMenuItemClick(new LikeComparator(
										0));

								break;
							case 1:
								bgTask.onOptionMenuItemClick(new LikeComparator(
										1));
								break;
							case 2:
								bgTask.onOptionMenuItemClick(new TimeComparator(
										0));
								break;
							case 3:
								bgTask.onOptionMenuItemClick(new TimeComparator(
										1));
								break;
							case 4:
								bgTask.onOptionMenuItemClick(new ViewComparator(
										0));
								break;
							case 5:
								bgTask.onOptionMenuItemClick(new ViewComparator(
										1));
								break;
							case 6:
								bgTask.onOptionMenuItemClick(new DateComparator());
								break;
							}
						}
					});

			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.main, menu);

		return true;
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (popup != null) {
			AlertDialog.Builder builder = new Builder(HomeActivity.this);
			builder.setTitle(getResources().getString(R.string.pop_up_title))
					.setMessage(popup.name)
					.setNegativeButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method
									// stub
									dialog.dismiss();
									Intent intent1 = new Intent();
									intent1.setAction(Intent.ACTION_VIEW);
									intent1.addCategory(Intent.CATEGORY_BROWSABLE);
									intent1.setData(Uri.parse(popup.url));
									startActivity(intent1);
									finish();
								}
							})
					.setNeutralButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
									finish();
								}
							});
			AlertDialog dialog = builder.create();
			;
			dialog.show();
		} else {
			super.onBackPressed();
		}
	}

	public void onEventMainThread(GetPopUpSuccessEvent e) {
		popup = e.banner;
	}

	public void onEventMainThread(OnMenuItemClickEvent e) {
		Log.e("",
				"OnMenuItemClickEvent " + e.getPlaylist_id() + " "
						+ e.getTitle());
		getSupportActionBar().setTitle(e.getTitle());
		if (viewPager.getCurrentItem() == 0) {
			toggle();
		} else {
			viewPager.setCurrentItem(0);
			toggle();
		}
	}

	boolean ask_for_check_update = false;

	public void onEventMainThread(GetAccesstokenSuccessEvent e) {

		String access_token = e.access_token;
		if (access_token != null) {
			bgTask.getPopUp(access_token);
			if (!ask_for_check_update)
				bgTask.checkUpDate(access_token);
		}
	}

	public void onEventMainThread(CheckUpdateSuccessEvent e) {
		try {
			JSONObject data = e.object;
			boolean status = data.getBoolean("status");
			if (status) {
				JSONObject dataDetail = data.getJSONObject("data");
				boolean force_update = dataDetail.getBoolean("force_update");
				String title_message = "";
				String content_message = "";
				final String update_uri = dataDetail.getString("update_uri");
				JSONObject messageJson = dataDetail.getJSONObject("message");
				title_message = messageJson.getString("title");
				content_message = messageJson.getString("message");
				content_message = content_message.replaceAll("</br>", "");
				AlertDialog.Builder builder = new Builder(HomeActivity.this);
				builder.setTitle(title_message);
				builder.setMessage(content_message);
				builder.setPositiveButton(
						getResources().getString(R.string.ok),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								DownloadFile downloadFile = new DownloadFile(
										HomeActivity.this);
								downloadFile.execute(update_uri);
							}
						});
				if (force_update) {
					// go to link update & install the latest update
				} else {

					builder.setNegativeButton(
							getResources().getString(R.string.cancel),
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.dismiss();
								}
							});
				}
				builder.create();
				builder.setCancelable(false);
				builder.show();
			}
		} catch (Exception ex) {
			// TODO: handle exception
			ex.printStackTrace();
		}
	}

	private class HomeFragmentAdapter extends FragmentStatePagerAdapter {

		protected String[] TITLE = new String[] {
				res.getString(R.string.app_name).toUpperCase(Locale.US),
				res.getString(R.string.top_download).toUpperCase(Locale.US) };

		public HomeFragmentAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			if (position == 0) {
				VideoFragment videoFragment = new VideoFragment();
				return videoFragment;
			} else {
				HomeListFragment listFragment = new HomeListFragment();
				Bundle bundle = new Bundle();
				bundle.putString(Constants.TOP, TITLE[position]);
				bundle.putString(Constants.STORE_KEY, "home");
				listFragment.setArguments(bundle);
				return listFragment;
			}
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return TITLE.length;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			// TODO Auto-generated method stub
			return TITLE[position];
		}

		@Override
		public void setPrimaryItem(ViewGroup container, int position,
				Object object) {
			// TODO Auto-generated method stub
			if (position == 1) {
				HomeListFragment frag = (HomeListFragment) object;
				frag.init();
			}

		}
	}

	@Override
	public void onClosed() {
		// TODO Auto-generated method stub

	}

}
